#!usr/bin/node

const http = require('http'),
      fs = require('fs');

http.createServer((req,res) => {
  let data = '',
      filename = '',
      filecontent = '';

  if(req.url === '/') {
    if(req.method === 'POST') {
      req.setEncoding('binary');
      req.on('data',chunk => {
        data += chunk;
      });
      req.on('end',() => {
        console.log(data);
        data = data.split('\r\n');
        filename = data[1].split(';');
        filename = filename[filename.length-1].split('=');
        filename = filename[1];
        filename = filename.substring(1,filename.length-1);
        console.log("filename:",filename);
        filecontent = data[4];
        console.log("filecontent:",filecontent);

        fs.writeFileSync(filename,filecontent);

        res.end('ok');
      });
    }else if(req.method === 'GET') {
      res.end('ok');
    }else{
      res.statusCode = 404;
      res.end('Request method not supported')
    }
  }
}).listen(8080);

